package registry

import (
	"barge/app"
	"barge/pkg/uix"
	"github.com/pkg/errors"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// deleteCmd represents the base command when called without any subcommands
var deleteCmd = &cobra.Command{
	Use: "delete",
	Aliases: []string{
		"del",
		"remove",
		"rm",
	},
	Short: "中转服务器配置",
	Long:  ``,
	Args: func(cmd *cobra.Command, args []string) error {
		if len(args) > 0 && deleteName == "" {
			deleteName = args[0]
		}
		if viper.GetBool("interactive") {
			if deleteName == "" {
				deleteName = uix.Input("请输入镜像仓库名称：")
			}
		}
		if deleteName == "" {
			return errors.New("镜像仓库名称不能为空")
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		m, err := app.NewConfigManager(viper.GetString("configPath"))
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
		m.DeleteRegistry(deleteName)
		err = m.Save()
		if err != nil {
			log.Err(err).Str("path", viper.GetString("configPath")).Send()
			return
		}
	},
}

var deleteName string

func init() {
	registryCmd.AddCommand(deleteCmd)
	deleteCmd.Flags().StringVarP(&deleteName, "name", "n", "", "镜像仓库名称")
}
